<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {
    public $render_data;
    
    function __construct() {
        parent::__construct();
        $this->load->library('carabiner');
        
    }
    
    function facebook_callback(){
        $this->config->load("facebook", TRUE);
        $config = $this->config->item('facebook');
        $this->load->library('Facebook', $config);

        $userId = $this->facebook->getUser();

               
        // If user is not yet authenticated, the id will be zero
        if ($userId == 0) {
            redirect(base_url());
        } else {
            redirect(base_url('register'));
        }
        
    }
    function index($lang='th')
    {
        $this->render_data['lang'] = $lang;
        
        $this->config->load("facebook", TRUE);
        $config = $this->config->item('facebook');
        $this->load->library('Facebook', $config);

        $userId = $this->facebook->getUser();

        $create_url = base_url('register');
        
        // If user is not yet authenticated, the id will be zero
        if ($userId == 0) {
            // Generate a login url
            $callback_url = base_url('frontend/home/facebook_callback');
            $register_url = $this->facebook->getLoginUrl(
                    array(  'scope' => 'email',
                            'redirect_uri' => $callback_url
                ));
        } else {
            // Get user's data and print it
            $user = $this->facebook->api('/me');
            $userId = $user['id'];
            $register_url = $create_url;
        }
        $this->render_data['register_url'] = $register_url;
        $this->render_data['user_id'] =$userId;
        
        $base_url  = base_url();
        $this->render_data['login_url'] = $this->facebook->getLoginUrl(
                    array(  'scope' => 'email',
                            'redirect_uri' => $base_url
                ));
        
        $this->render_data['register_url'] = '#';
        $this->render_data['login_url'] = '#';

        $this->load->view('frontend/home',$this->render_data);
    }
    
    function logout(){
        $this->config->load("facebook", TRUE);
        $config = $this->config->item('facebook');
        $this->load->library('Facebook', $config);
       
        $this->facebook->destroySession();
        redirect(base_url());
    }
    
}